const fs = require('fs')
const path = require('path')

// 定义存储所有 package.json 信息的数组
const packagesInfo = []

// 获取 node_modules 目录路径
const nodeModulesPath = path.join(__dirname, 'node_modules')

// 递归读取所有 package.json 文件
function readPackageJsonFiles(dir) {
  const files = fs.readdirSync(dir)


  for (let index = 0; index < files.length; index++) {
    const file = files[index]
    const filePath = path.join(dir, file)

    // 检查是否为目录
    if (fs.statSync(filePath).isDirectory()) {
      // 递归读取目录
      readPackageJsonFiles(filePath)
    } else if (file === 'package.json') {
      // 读取 package.json 文件
      const content = fs.readFileSync(filePath, 'utf-8')
      try {
        const packageInfo = JSON.parse(content)

        // 提取所需属性
        let { name, version, license } = packageInfo
        if(!name) continue
        let group
        if (name.startsWith('@')) {
          let groupAndName = name.split('/')
          if (groupAndName.length >= 2) {
            group = groupAndName[0]
            name = groupAndName[1]
            if (name.length <= 0) {
              group = undefined
              name = groupAndName
            }
          } else {
            name = groupAndName
          }
        } else {
          group = undefined
        }
        // 添加到数组
        packagesInfo.push({
          group: group || "",
          name,
          version,
          license,
        })
      } catch (err) {
        console.log('err: ', err)
      }
    }
  }
}

// 开始递归读取
readPackageJsonFiles(nodeModulesPath)

// 将结果写入新的 JSON 文件
console.log('packagesInfo: ', packagesInfo)
const outputFilePath = path.join(__dirname, 'node_modules_info.json')
fs.writeFileSync(outputFilePath, JSON.stringify(packagesInfo, null, 2))
